package com.siss.tenancy.util;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

public class EncryptUtil {
    public static String MD2 = "MD2";
    public static String MD5 = "MD5";
    public static String SHA1 = "SHA-1";
    public static String SHA256 = "SHA-256";
    public static String SHA384 = "SHA-384";
    public static String SHA512 = "SHA-512";
	private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5',
			'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
	
	private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
		"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

	/**
	 * encode string
	 *
	 * @param algorithm
	 * @param str
	 * @return String
	 */
	public static String encode(String algorithm, String str) {
		if (str == null) {
			return null;
		}
		try {
			MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
			messageDigest.update(str.getBytes());
			return getFormattedText(messageDigest.digest());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

	}

	/**
	 * encode By MD5
	 *
	 * @param str
	 * @return String
	 */
	public static String encodeByMD5(String str) {
		if (str == null) {
			return null;
		}
		try {
			MessageDigest messageDigest = MessageDigest.getInstance(MD5);
			messageDigest.update(str.getBytes());
			return getFormattedText(messageDigest.digest());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

	}

	/**
	 * Takes the raw bytes from the digest and formats them correct.
	 *
	 * @param bytes
	 *            the raw bytes from the digest.
	 * @return the formatted bytes.
	 */
	private static String getFormattedText(byte[] bytes) {
		int len = bytes.length;
		StringBuilder buf = new StringBuilder(len * 2);
		// 把密文转换成十六进制的字符串形式
		for (int j = 0; j < len; j++) { 			buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
			buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
		}
		return buf.toString();
	}
    /**
     * 返回SHA1加密串
     * @param str
     * @return
     */
    public static String getSha1(String str,String charset){
    	return encrypt(str, EncryptUtil.SHA1,charset);
    }
    
    /**
     * 返回SHA1加密串
     * @param str
     * @return
     */
    public static String getSha1(String str){
    	return encrypt(str, EncryptUtil.SHA1);
    }
    
    /**
     * 返回md5加密串
     * @param str
     * @return
     */
    public static String getMD5(String str,String charset){
    	return encrypt(str, EncryptUtil.MD5,charset);
    }
    /**
     * @param str
     *            加密明文
     * @param algorithm
     *            加密算法
     * @return 加密结果字符串
     */
    public static String encrypt(String str, String algorithm,String charset) {
        try {
        	byte[] strByte=str.getBytes(charset);
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            messageDigest.reset();
            messageDigest.update(strByte);
            byte[] res = messageDigest.digest();
            return byte2hex(res);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return str;
        } catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return str;
		}
    }
    
    /**
     * @param str
     *            加密明文
     * @param algorithm
     *            加密算法
     * @return 加密结果字符串
     */
    public static String encrypt(String str, String algorithm) {
        try {
        	byte[] strByte=str.getBytes();
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            messageDigest.reset();
            messageDigest.update(strByte);
            byte[] res = messageDigest.digest();
            return byte2hex(res);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return str;
        }
    }
 
    /**
     * 将byte数组转换为16进制表示
     * 
     * @param byteArray
     * @return
     */
    private static String byte2hex(byte[] byteArray) {
        StringBuffer md5StrBuff = new StringBuffer();
        for (int i = 0; i < byteArray.length; i++) {
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {
                md5StrBuff.append("0").append(
                        Integer.toHexString(0xFF & byteArray[i]));
            } else {
                md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
            }
 
        }
        return md5StrBuff.toString();
    }
    
    private static String byteArrayToHexString(byte b[]) {
		StringBuffer resultSb = new StringBuffer();
		for (int i = 0; i < b.length; i++)
			resultSb.append(byteToHexString(b[i]));

		return resultSb.toString();
	}

	private static String byteToHexString(byte b) {
		int n = b;
		if (n < 0)
			n += 256;
		int d1 = n / 16;
		int d2 = n % 16;
		return hexDigits[d1] + hexDigits[d2];
	}

	public static String MD5Encode(String origin, String charsetname) {
		String resultString = null;
		try {
			resultString = new String(origin);
			MessageDigest md = MessageDigest.getInstance("MD5");
			if (charsetname == null || "".equals(charsetname))
				resultString = byteArrayToHexString(md.digest(resultString
						.getBytes()));
			else
				resultString = byteArrayToHexString(md.digest(resultString
						.getBytes(charsetname)));
		} catch (Exception exception) {
		}
		return resultString;
	}
    
    public static void main(String[] args) throws UnsupportedEncodingException {
    	//String cardStr="jz02356,1,4,2015-04-30";
    	////System.out.println(getSha1(cardStr));
    	  UUID uuid = UUID.randomUUID();
          System.out.println(uuid.toString().replaceAll("-", ""));
	}
 
//    public void test() {
//        String str = "456789srba_wx_2014";
//        //61fad161599c0a2bea9f75d67caf020ba9f43dcf 
//        //System.out.println(EncryptUtil.encrypt(str, EncryptUtil.MD5).toLowerCase());
//        Assert.assertEquals("202cb962ac59075b964b07152d234b70",EncryptUtil.encrypt(str, EncryptUtil.MD5));
//        //System.out.println(EncryptUtil.encrypt(str, EncryptUtil.SHA1));
//        Assert.assertEquals("40bd001563085fc35165329ea1ff5c5ecbdbbeef",EncryptUtil.encrypt(str, EncryptUtil.SHA1));
//    }
}